package dto

type OrganizeDto struct {
	Id int64 `json:"id,omitempty"  gorm:"primaryKey"`

	Name string `json:"name"`
	Type string `json:"type"` //组织类型，自行定义
	Pid  int64  `json:"pid"`

	Status int `json:"status,omitempty" ` //组织状态，0：无，1：正常，2：禁用，其他自行定义

	Children []*OrganizeDto `json:"children,omitempty" gorm:"-"` //子节点列表
}

// OrganizeDtoConvertTree 转为树型结构
func OrganizeDtoConvertTree(list []*OrganizeDto) []*OrganizeDto {
	dataMap := map[int64]*OrganizeDto{}
	var tree []*OrganizeDto
	for {
		var l = 0
		for _, v := range list {
			if _, exist := dataMap[v.Id]; exist {
				continue
			}

			if v.Pid == 0 {
				tree = append(tree, v)
				dataMap[v.Id] = v
				l++
			}

			if _, exist := dataMap[v.Pid]; exist {
				parent := dataMap[v.Pid]
				parent.Children = append(parent.Children, v)
				dataMap[v.Id] = v
				l++
			}
		}
		if l == 0 {
			break
		}
	}
	return tree
}

// FindOrganizeTreeNode 查找树的指定节点
func FindOrganizeTreeNode(list []*OrganizeDto, id int64) *OrganizeDto {
	if len(list) == 0 {
		return nil
	}
	for _, v := range list {
		if v.Id == id {
			return v
		}
		if tmp := FindOrganizeTreeNode(v.Children, id); tmp != nil {
			return tmp
		}
	}
	return nil
}
